﻿using System;
using System.Reactive.Subjects;
using System.Reactive.Linq;
using System.Windows.Forms;

namespace Demo
{
    public partial class SubjectTypesForm : Form
    {

		public SubjectTypesForm()
        {
            InitializeComponent();
        }

		private void replaySubjectBtn_Click(object sender, EventArgs e)
		{
			listBox1.Items.Add("-----------------------------------");
			listBox1.Items.Add("ReplaySubject remembers all publications");
			var subject = new ReplaySubject<string>();

			subject.OnNext("first");
            subject.OnNext("b");
            subject.OnNext("c");
			
			SubscribeToStream(subject);

			subject.OnNext("d");
			subject.OnNext("this should be the last item shown");

			subject.OnCompleted();

			subject.OnNext("this will not be shown");
		}


		private void behaviorSubjectBtn_Click(object sender, EventArgs e)
		{
			listBox1.Items.Add("-----------------------------------");
			listBox1.Items.Add("BehaviorSubject shows last entry and all future entries");

			listBox1.Items.Add("");
			listBox1.Items.Add("BehaviorSubject with empty list");
			var subject = new BehaviorSubject<string>("defaultVal");
			SubscribeToStream(subject);

			listBox1.Items.Add("");
			listBox1.Items.Add("BehaviorSubject with single item list");
			var subject2 = new BehaviorSubject<string>("defaultVal");
			subject2.OnNext("a");
			subject2.OnNext("b");
			SubscribeToStream(subject2);

			listBox1.Items.Add("");
			listBox1.Items.Add("BehaviorSubject with multi item list");
			var subject3 = new BehaviorSubject<string>("defaultVal");
			subject3.OnNext("a");
			subject3.OnNext("b");
			SubscribeToStream(subject3);
			subject3.OnNext("c");
			subject3.OnNext("d");

		}

    	private AsyncSubject<string> asyncSubject;
		private void asyncSubjectBtn_Click(object sender, EventArgs e)
		{
			listBox1.Items.Add("-----------------------------------");
			listBox1.Items.Add("AsyncSubject shows only last entry, but only after end");

			asyncSubject = new AsyncSubject<string>();
			asyncSubject.OnNext("a");
			asyncSubject.OnNext("b");
			SubscribeToStream(asyncSubject);
			asyncSubject.OnNext("c");
			asyncSubject.OnNext("d");
			listBox1.Items.Add("AsyncSubject waiting for end");
		}

		private void button2_Click(object sender, EventArgs e)
		{
			asyncSubject.OnCompleted();
		}

        private void button3_Click(object sender, EventArgs e)
        {
            asyncSubject.OnError(new Exception("Brad screwed up"));
        }

        private void SubscribeToStream(IObservable<string> stream)
		{
			listBox1.Items.Add("   subscribing");
			stream.Subscribe(
				x => listBox1.Items.Add(x),
				x => listBox1.Items.Add("Error published " + x.Message),
				() => listBox1.Items.Add("OnComplete"));
		}

		private void button1_Click(object sender, EventArgs e)
		{
			listBox1.Items.Clear();
		}



    }

}
